import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Table, Typography } from 'antd';
import { 
  UserOutlined, 
  BookOutlined, 
  FileTextOutlined, 
  TrophyOutlined,
  SafetyCertificateOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';
import { api } from '../utils/api';

const { Title } = Typography;

interface DashboardStats {
  total_users: number;
  total_articles: number;
  total_exams: number;
  total_certificates: number;
  total_questions: number;
  total_exam_records: number;
}

interface RecentExamRecord {
  id: number;
  user: {
    nickname: string;
  };
  exam: {
    title: string;
  };
  score: number;
  is_passed: boolean;
  created_at: string;
}

const Dashboard: React.FC = () => {
  const [stats, setStats] = useState<DashboardStats>({
    total_users: 0,
    total_articles: 0,
    total_exams: 0,
    total_certificates: 0,
    total_questions: 0,
    total_exam_records: 0
  });
  const [recentRecords, setRecentRecords] = useState<RecentExamRecord[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      
      // 获取统计数据
      const statsResponse = await api.get('/system/stats');
      if (statsResponse.data.success) {
        setStats(statsResponse.data.data);
      }
      
      // 获取最近的考试记录
      const recordsResponse = await api.get('/exams/admin/records?per_page=10');
      console.log('recordsResponse:',recordsResponse);
      if (recordsResponse.data.success) {
        setRecentRecords(recordsResponse.data.data.items || []);
      }
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const recentRecordsColumns = [
    {
      title: '用户',
      dataIndex: ['user', 'nickname'],
      key: 'user',
    },
    {
      title: '考试',
      dataIndex: ['exam', 'title'],
      key: 'exam',
    },
    {
      title: '得分',
      dataIndex: 'score',
      key: 'score',
      render: (score: number) => `${score}分`,
    },
    {
      title: '状态',
      dataIndex: 'is_passed',
      key: 'status',
      render: (isPassed: boolean) => (
        <span style={{ color: isPassed ? '#52c41a' : '#ff4d4f' }}>
          {isPassed ? '通过' : '未通过'}
        </span>
      ),
    },
    {
      title: '时间',
      dataIndex: 'end_time',
      key: 'end_time',
      render: (date: string) => new Date(date).toLocaleString(),
    },
  ];

  return (
    <div>
      <Title level={2}>仪表盘</Title>
      
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={stats.total_users}
              prefix={<UserOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="文章数量"
              value={stats.total_articles}
              prefix={<BookOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="考试数量"
              value={stats.total_exams}
              prefix={<FileTextOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="证书数量"
              value={stats.total_certificates}
              prefix={<SafetyCertificateOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="题目数量"
              value={stats.total_questions}
              prefix={<QuestionCircleOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="考试记录"
              value={stats.total_exam_records}
              prefix={<TrophyOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>

      {/* 最近考试记录 */}
      <Card title="最近考试记录" style={{ marginBottom: 24 }}>
        <Table
          columns={recentRecordsColumns}
          dataSource={recentRecords}
          rowKey="id"
          pagination={false}
          loading={loading}
          size="small"
        />
      </Card>
    </div>
  );
};

export default Dashboard; 